package edu.ccut.titan.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;

import edu.ccut.titan.service.ITitanPropertiesService;

public class TitanPropertiesService implements ITitanPropertiesService {

	private static ITitanPropertiesService instance;
	
	private static final String TITAN_PROPERTIES_NAME = "titan.properties";
	
	static {
		instance = new TitanPropertiesService();
	}
	
	private Properties properties = new Properties();
	
	private TitanPropertiesService() {
		this.addProperties(System.getProperties());
		this.addProperties(this.getTitanProperties());
	}
	
	public static ITitanPropertiesService getInstance() {
		return instance;
	}

	@SuppressWarnings("unchecked")
	public void addProperties(Properties properties) {
		Enumeration keys = properties.propertyNames();
		
		synchronized (this.properties) {
			while (keys.hasMoreElements()) {
				String key = (String) keys.nextElement();
				this.setProperty(key, properties.getProperty(key));
			}
		}
	}

	public synchronized String getProperty(String name) {
		return this.properties.getProperty(name);
	}

	@SuppressWarnings("unchecked")
	public synchronized Enumeration getPropertyNames() {
		return this.properties.propertyNames();
	}

	public synchronized void setProperty(String name, String value) {
		this.properties.setProperty(name, value);
	}
	
	private synchronized Properties getTitanProperties() {
		Properties properties = new Properties();
		InputStream in = null;
		try {
			in = ITitanPropertiesService.class.getResourceAsStream(TITAN_PROPERTIES_NAME);
			if (in != null) {
				properties.load(in);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return properties;
	}
}
